package com.ruoyi.pointRecord.dao.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.CodeGeneratorUtil;
import com.ruoyi.pointRecord.dao.IProductReturnDao;
import com.ruoyi.pointRecord.domain.PointsExchangeRecord;
import com.ruoyi.pointRecord.mapper.PointsExchangeRecordMapper;
import com.ruoyi.points.dao.IPointsChangeRecordDao;
import com.ruoyi.product.mapper.PointsProductInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class ProductReturnDaoImpl extends ServiceImpl<PointsExchangeRecordMapper, PointsExchangeRecord> implements IProductReturnDao {

    @Autowired
    private IPointsChangeRecordDao pointsChangeRecordDao;

    @Autowired
    private PointsExchangeRecordMapper pointsExchangeRecordMapper;

    @Autowired
    private PointsProductInfoMapper pointsProductInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void processExchangeReversal(PointsExchangeRecord record, Long newStatus, Long pointsType, String failMessage) {
        // 1. 退还积分
        String batchCode = CodeGeneratorUtil.generateBatchCode();
        int pointsResult = pointsChangeRecordDao.recordAndUpdatePoints(
                record.getUserId(),
                record.getPointsCost(),
                pointsType,
                batchCode
        );
        if (pointsResult <= 0) {
            throw new RuntimeException("积分退还失败：" + failMessage);
        }

        // 2. 恢复库存
        restoreProductStock(record.getProductId(), record.getExchangeQuantity());

        // 3. 更新订单状态
        record.setExchangeStatus(newStatus);
        int result = pointsExchangeRecordMapper.updatePointsExchangeRecord(record);
        if (result <= 0) {
            throw new RuntimeException("更新兑换记录失败：" + failMessage);
        }
    }

    private void restoreProductStock(Long productId, Long returnQuantity) {
        int result = pointsProductInfoMapper.restoreStockAndSales(productId, returnQuantity);
        if (result <= 0) {
            throw new RuntimeException("恢复商品库存失败");
        }
    }
}
